import logging
from pathlib import Path
from typing import Any, Dict, List, Optional

from fastapi_mail import FastMail, MessageSchema, ConnectionConfig
from pydantic import EmailStr

logger = logging.getLogger(__name__)

class EmailNotConfigured(Exception):
    """当邮件服务未配置时抛出的异常"""
    pass

# 邮件配置（应从环境变量或配置文件中加载）
email_config = ConnectionConfig(
    MAIL_USERNAME="your-email@example.com",
    MAIL_PASSWORD="your-password",
    MAIL_FROM="your-email@example.com",
    MAIL_PORT=587,
    MAIL_SERVER="smtp.example.com",
    MAIL_TLS=True,
    MAIL_SSL=False,
    USE_CREDENTIALS=True,
    VALIDATE_CERTS=True,
    TEMPLATE_FOLDER=Path(__file__).parent / "../templates/email"
)

async def send_email(
    email_to: List[EmailStr],
    subject: str,
    body: str,
    template_name: Optional[str] = None,
    template_body: Optional[Dict[str, Any]] = None
) -> None:
    """
    发送电子邮件
    
    Args:
        email_to: 收件人列表
        subject: 邮件主题
        body: 邮件正文（纯文本）
        template_name: 模板名称（如果使用模板）
        template_body: 模板变量（如果使用模板）
    """
    try:
        # 创建消息
        message = MessageSchema(
            subject=subject,
            recipients=email_to,
            body=body,
            subtype="html" if template_name else "plain"
        )
        
        # 发送邮件
        fm = FastMail(email_config)
        
        if template_name and template_body:
            await fm.send_message(message, template_name=template_name, template_body=template_body)
        else:
            await fm.send_message(message)
            
        logger.info(f"Email sent to {email_to}")
    except Exception as e:
        logger.error(f"Failed to send email: {str(e)}")
        raise